/**
 * 入参
 *
 */
import React, { PureComponent } from 'react';
import { InputC, SelectC } from '../../../../comps';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import { connect } from 'dva';
import style from '../index.less';
import colors from '../../../../css/colors';
import { formSelectData } from '../../../../utils/utils';

const redColor = colors.debtAndProfit.text[0];
const disabledColor = colors.debtAndProfit.text[4];
const mainColor = colors.debtAndProfit.text[5];
@Form.create()
class AccountC extends PureComponent {
  state = {
    accountList: [{}],
  };
  componentDidMount() {
    this.props.onRef(this);
    this.setState({
      accountList: this.props.data,
    });
  }
  //add 新增
  add = () => {
    const { accountList } = this.state;
    if (!this.props.isExtra) return; //外部通道关闭 则返回
    const nextList = accountList.concat({});
    this.props.form.setFieldsValue({ account: [...nextList] }); //accountList不能更新form表单，form表单也必须更新值，负责增减都会有问题
    this.setState({
      accountList: [...nextList],
    });
  };
  del = (index) => {
    const { accountList } = this.state;
    if (accountList.length === 1) {
      //剩余一条不可删除
      return;
    }
    const nextList = accountList.filter((item, key) => key !== index);
    this.props.form.setFieldsValue({ account: [...nextList] }); //accountList不能更新form表单，form表单也必须更新值，负责增减都会有问题
    this.setState({
      accountList: [...nextList],
    });
  };
  //提交
  submit = () => {
    var obj;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        obj = values;
      }
    });
    return obj;
  };
  //校验是否重复
  checkAccountType = (rule, value, callback, index) => {
    const {
      form: { getFieldsValue, validateFields },
    } = this.props;
    const tempArr = getFieldsValue().account;
    const arr = [];
    tempArr.map((item, key) => {
      if (key != index) {
        //除去自己 比对是否有重复
        //当交易通道选择PB时，操作员编号支持录入多个，不进行校验
        if (this.props.channel == 'PB' && item.accountType == 'OPERATOR_ID') {
          return;
        }
        let obj = JSON.parse(JSON.stringify(item));
        obj.key = key;
        arr.push(obj);
      }
    });
    if (arr.find((item) => item.accountType == value && value)) {
      callback('账户类型不能重复');
    } else {
      if (this.field === rule.field) {
        const remainArr = [];
        arr.map((item, index) => {
          remainArr.push(`account[${item.key}].accountType`);
        });
        validateFields(remainArr, { force: true });
      }
      callback();
    }
  };
  //校验是否重复
  checkAccountCode = (rule, value, callback, index) => {
    const {
      form: { getFieldsValue, validateFields },
    } = this.props;
    const tempArr = getFieldsValue().account;
    const arr = [];
    tempArr.map((item, key) => {
      if (key != index) {
        //除去自己 比对是否有重复
        let obj = JSON.parse(JSON.stringify(item));
        obj.key = key;
        arr.push(obj);
      }
    });
    if (arr.find((item) => item.accountCode == value && value)) {
      callback('账户代码不能重复');
    } else {
      if (this.field === rule.field) {
        const remainArr = [];
        arr.map((item, index) => {
          remainArr.push(`account[${item.key}].accountCode`);
        });
        validateFields(remainArr, { force: true });
      }
      callback();
    }
  };
  onChange = (index, name, event, field) => {
    //校验重复 需要accountList  这里更新数据
    const { accountList } = this.state;
    this.field = field;
    let tempArray = [...accountList];
    if ('accountType' === name) tempArray[index] = { ...tempArray[index], accountType: event };
    else tempArray[index] = { ...tempArray[index], accountCode: event.target.value };
    this.setState({
      accountList: [...tempArray],
    });
  };
  //reset 重置数据
  reset = () => {
    const arr = [{}];
    this.setState({
      accountList: [...arr],
    });
    this.props.form.resetFields();
    this.field = undefined;
  };

  render() {
    const {
      isExtra,
      globalM: { dataDictionary },
      channel,
    } = this.props;
    const { accountList } = this.state;
    let selectList =
      channel == undefined
        ? []
        : channel == 'MATIC'
        ? formSelectData(dataDictionary.CommandConfigAccountName || [])
        : channel != 'EXTERNAL_PB'
        ? formSelectData(dataDictionary.NUMBERTYPE_DICT || []).filter((item) => !['H_NUMBER', 'S_NUMBER'].includes(item.value))
        : formSelectData(dataDictionary.NUMBERTYPE_DICT || []);
    return (
      <div className={'account_list'}>
        <Form.Item label='账户信息' className={isExtra ? 'accountLabel' : ''}>
          <div style={{ height: 'auto', maxHeight: '215px', overflowY: 'auto' }}>
            {accountList &&
              accountList.map((item, index) => {
                return (
                  <Row key={index}>
                    <Col span={10} className='itemWidth'>
                      <SelectC
                        form={this.props.form} // form对象
                        dataIndex={`account[${index}].accountType`} // Form识别的Item ID
                        dataSource={selectList}
                        initialValue={item.accountType}
                        showSearch={false}
                        rules={[{ required: isExtra, message: '账户类型必填' }, { validator: (rule, value, callback) => this.checkAccountType(rule, value, callback, index) }]}
                        disabled={!isExtra}
                        placeholder={'请选择账户类型'}
                        onChange={(event) => this.onChange(index, 'accountType', event, `account[${index}].accountType`)}
                        positionBody={true}
                      />
                    </Col>
                    <Col span={1} className={'width10'}>
                      {' '}
                    </Col>
                    <Col span={10} className='itemWidth'>
                      <div style={{ paddingBottom: ' 8px' }}>
                        <InputC
                          form={this.props.form} // form对象
                          dataIndex={`account[${index}].accountCode`} // Form识别的Item ID
                          initialValue={item.accountCode}
                          rules={[{ required: isExtra, message: '账户代码必填' }, { validator: (rule, value, callback) => this.checkAccountCode(rule, value, callback, index) }]}
                          disabled={!isExtra}
                          placeholder={'请输入账户代码'}
                          onChange={(event) => this.onChange(index, 'accountCode', event, `account[${index}].accountCode`)}
                        />
                      </div>
                    </Col>
                    <Col span={1} className={'width10'}>
                      {' '}
                    </Col>
                    <MinusCircleOutlined
                      className={'icon_minus'}
                      style={{ color: this.state.accountList.length == 1 ? disabledColor : redColor }}
                      onClick={() => this.del(index)}
                    />
                  </Row>
                );
              })}
          </div>
        </Form.Item>
        <PlusCircleOutlined className={'icon_minus add_icon'} style={{ color: !isExtra ? disabledColor : mainColor }} onClick={this.add} />
      </div>
    );
  }
}
export default connect(({ globalM }) => ({
  globalM,
}))(AccountC);
